package com.jy.modules.cims.common.open.api.crypt;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.jy.modules.cims.common.open.api.exception.JieYueApiException;

public class AESCrypt {
	private Charset charset = Charset.forName("UTF-8");
	private String aesKey;
	private Base64 base64 = new Base64();

	public AESCrypt(String aesKey, Charset charset) {
		this.aesKey = aesKey;
		this.charset = charset;
	}

	public AESCrypt(String aesKey) {
		this.aesKey = aesKey;
	}

	public String encrypt(String content) {
		try {
			Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
			SecretKeySpec key = new SecretKeySpec(this.aesKey.getBytes(this.charset), "AES");
			aesECB.init(1, key);
			byte[] result = aesECB.doFinal(content.getBytes(this.charset));
			return this.base64.encodeToString(result);
		} catch (Exception e) {
			throw new JieYueApiException("base64编码失败", e);
		}
	}

	public String decrypt(String content) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			SecretKeySpec key = new SecretKeySpec(this.aesKey.getBytes(this.charset), "AES");
			cipher.init(2, key);
			byte[] result = Base64.decodeBase64(content);
			return new String(cipher.doFinal(result), this.charset);
		} catch (Exception e) {
			throw new JieYueApiException("", e);
		}
	}
}
